<?php

use yii\helpers\VarDumper;
use common\models\OmsOrderGoods;
use common\models\OmsOrderInfo;
use linslin\yii2\curl\Curl;
use common\models\BaseImg;
use common\models\BaseSupplierGoods;
use common\models\SysSupplier;
use common\models\BaseChannel;
use common\models\SaleLadderPrice;
use common\models\SysRedBagUser;
use common\models\SysUser;
use common\models\OutNew;
use common\models\LadderGroupPrice;
use common\models\BaseOrderMinusGoods;
use common\util\F;
use common\models\BaseGoodsSite;
use yii\db\Query;

/* ============================================
 * 时间：2014年11月16日 22:54:19
 * 说明：常用工具类函数文件
 * 约定以"f_"前缀开头
 * ============================================  
 */

/**
 * @Title: f_f
 * @Description: 一次性提示信息 
 * @return: return_type
 * @author: kai.gao
 * @date: 2014-12-2 下午2:50:14
 */
function f_f($key, $val = null) {
    return $val != null ? \Yii::$app->session->setFlash($key, $val) : \Yii::$app->session->getFlash($key, $val);
}

/**
 * @Title: f_img
 * @Description: 获取图片的完整路径 
 * @param integer $img_id 图片的id
 * @return: string
 * @author: kai.gao
 * @date: 2014-12-19下午10:43:11
 */
function f_img($img_id) {
    $model = BaseImg::findOne($img_id);
    return is_object($model) ? IMAGE_URL . '/' . $model->img_url : IMAGE_URL . '/undefined.jpg';
}

/**
 * @Title: f_tips
 * @Description: 获取提示信息 
 * @param integer $tips_id 提示信息ID
 * @return: string
 * @author: xiangjin.shen
 * @date: 2015年7月1日 16:15:35
 */
function f_tips($tips_id) {
    $tips = common\models\SysMenuFaq::getMenuId($tips_id);
    if ($tips) {
        return $tips;
    } else {
        return "暂无信息";
    }
}

/**
 * @description:批量删除按钮
 * @return: string
 * @author: sunkouping
 * @date: 2015年7月9日上午11:03:48
 * @modified_date: 2015年7月9日上午11:03:48
 * @modified_user: sunkouping
 * @review_user:
 */
function f_removeall($key) {
    return "<button type='button' class='btn btn-success' style='margin-left:20px;' onclick='
 	        		var keys = $(&quot;#grid2015&quot;).yiiGridView(&quot;getSelectedRows&quot;).length;
 	        		if (keys &gt; 0) {
 						if (confirm(&quot;你确定要删除这条记录吗？&quot;)) {
 							$.ajax({
 								url : &quot;/common/delete-all&quot;,
 	        					data : {" . $key . "},
 	        					type : &quot;post&quot;,
 	        					success : function(data) {
 									window.location.reload();
 								}
 							})
 						}
 					} else {
 						alert(&quot;没有被选中的记录&quot;);
 					}'><i class='glyphicon glyphicon-remove'></i> 批量删除</button>";
}

/**
 * @Title: f_date
 * @Description: 
 * @param int $unixtime 时间戳
 * @param int or string $mode 
 * @return: string 1：年月日时分秒   2：年月日  3： 时分秒 
 * @author: 凯神;
 * @date: 2014-12-17 下午5:43:54
 */
function f_date($unixtime, $mode = 1) {
    $modes = [1 => 'Y-m-d H:i:s', 2 => 'Y-m-d', 3 => 'H:i:s'];
    return isset($modes[$mode]) ? date($modes[$mode], $unixtime) : date($mode, $unixtime);
}

/**
 * @Title: changeTimeType
 * @Description: 将秒转化为时、分、秒
 * @return: string
 * @author: weilong.yin
 * @date: 2015-5-19 上午10:22:10
 */
function f_seconds($seconds) {
    if ($seconds >= 86400) {
        $day = intval($seconds / 86400);
        $temp = $seconds - $day * 86400;
        $time = $day . "天" . gmstrftime('%H时%M分%S秒', $temp);
    } else if ($seconds >= 3600) {
        $hours = intval($seconds / 3600);
        $minutes = $seconds - $hours * 3600;
        $time = $hours . "时" . gmstrftime('%M分%S秒', $minutes);
    } else {
        $time = gmstrftime('%M分%S秒', $seconds);
    }
    return $time;
}

/**
 * @Title: f_remote_upload
 * @Description: 远程上传文件
 * @param string $dir 服务器文件夹
 * @param string $filename 本地完整文件路径
 * @param bool $delete 长传之后是否删除本地文件，默认删除 
 * @return: null or string
 * @author: kai.gao
 * @date: 2014-12-10 下午11:02:14
 */
function f_remote_upload($filename, $delete = true, $dir = 'default') {
    if (file_exists($filename)) {
        $curl = new Curl();
        $data = ['file' => '@' . $filename, 'dir' => $dir];
        $img_url = $curl->post(IMAGE_UPLOAD_URL, $data, false);

        if ($delete)
            @unlink($filename);
        return $img_url['img_url'];
    }
//    $imgName=  explode('/', $filename);
//    $filename=$imgName[count($imgName)-1];
//   return $filename;
}

/**
 * @Title: f_c cache
 * @Description: 封装获取和保存缓存的发那个发
 * @param mixed $key 键值
 * @param mixed $val 缓存的值
 * @param int $expire 过期时间
 * @return: mixed
 * @author: kai.gao
 * @date: 2014-12-1 下午12:35:28
 */
function f_c($key, $val = null, $expire = 0) {
    $cache = \Yii::$app->rcache;
    if ($val === false)
        $cache->delete($key);
    elseif ($val === null) {
        $data = $cache->get($key);
        //$data === false && Yii::error($key.'缓存不存在');
        return $data;
    } else
        $cache->set($key, $val, $expire);
}

/**
 * @Title: f_p
 * @Description: 封装获取配置文件参数的方法
 * @param string or int $index 索引 
 * @return: multitype:
 * @author: kai.gao
 * @date: 2014-12-1 下午3:03:04
 */
function f_p($index) {
    return isset(\Yii::$app->params[$index]) ? \Yii::$app->params[$index] : null;
}

/**
 * @Title: f_s session
 * @param string $key 要设置的key或者要获取的key
 * @param mixed $value 要设置的value false表示删除session
 * @param boolean $default 是否开启get默认值 
 * @return: Session or mixd
 * @author: kai.gao
 * @date: 2014-11-28 上午11:54:50
 */
function f_s($key, $value = false, $default = false) {
    $session = Yii::$app->session;
    if (!$default && $key !== null) {
        if ($value === false)
            return $session->get($key);
        elseif ($value === null)
            return $session->remove($key);
        else
            $session->set($key, $value);
    } elseif ($key === null) {
        return $session;
    } else {
        return $session->get($key, $value);
    }
}

/**
 * @Title: f_ck 
 * @Description:获取 设置 删除cookie 
 * @param string $key 键值
 * @param mixed $val 保存的内容 null表示是抓去内容 false表示删除内容 有内容表示设置
 * @param int cookie的生命周期，默认0
 * @param array $params cookie的其他参数
 * @return: string|NULL
 * @author: kai.gao
 * @date: 2014-12-1 下午3:51:11
 */
function f_ck($key, $val = null, $expire = 0, $params = []) {
    if ($val === false) {
        \Yii::$app->response->cookies->remove($key);
    } elseif (!is_null($val)) {
        $cookies = \Yii::$app->response->cookies;
        $params['name'] = $key;
        $params['value'] = $val;
        $params['expire'] = (int) $expire > 0 ? (int) $expire + time() : 0;
        $cookies->add(new \yii\web\Cookie($params));
    } else {
        if (isset(\Yii::$app->request->cookies[$key]))
            return (string) \Yii::$app->request->cookies[$key];
        else
            return null;
    }
}

/**
 * url生成函数
 * @param array $params ['site/index', 'param1' => 'value1', 'param2' => 'value2']
 * @return string 根据规则生成对应的url
 * @author kai.gao
 * @return link href地址
 */
function f_url($params) {
    return Yii::$app->urlManager->createUrl($params);
}

/**
 * 封装系统打印函数 dump
 * @param mixed $var 打印变量
 * @param string $is_exit 是否终止程序
 * @param number $depth 打印深度
 * @param string $highlight 高亮
 */
function f_d($var, $is_exit = true, $depth = 10, $highlight = true) {
    VarDumper::dump($var, $depth, $highlight);
    $is_exit && exit();
}

/**
 *
 * 字符串截取函数，防止截取中文乱码
 * @param String $sourcestr 截取的字符串对象
 * @param Integer $cutlength 截取的长度
 * @param String $etc 截取完的后缀，默认为'...'
 */
function f_sub($sourcestr, $cutlength = 80, $etc = '...') {
    $returnstr = '';
    $i = 0;
    $n = 0.0;
    $str_length = strlen($sourcestr);
    while (($n < $cutlength) and ( $i < $str_length)) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum = ord($temp_str);
        if ($ascnum >= 252) {
            $returnstr = $returnstr . substr($sourcestr, $i, 6);
            $i = $i + 6;
            $n++;
        } elseif ($ascnum >= 248) {
            $returnstr = $returnstr . substr($sourcestr, $i, 5);
            $i = $i + 5;
            $n++;
        } elseif ($ascnum >= 240) {
            $returnstr = $returnstr . substr($sourcestr, $i, 4);
            $i = $i + 4;
            $n++;
        } elseif ($ascnum >= 224) {
            $returnstr = $returnstr . substr($sourcestr, $i, 3);
            $i = $i + 3;
            $n++;
        } elseif ($ascnum >= 192) {
            $returnstr = $returnstr . substr($sourcestr, $i, 2);
            $i = $i + 2;
            $n++;
        } elseif ($ascnum >= 65 and $ascnum <= 90 and $ascnum != 73) {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            $n++;
        } elseif (!(array_search($ascnum, array(37, 38, 64, 109, 119)) === FALSE)) {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            $n++;
        } else {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            $n = $n + 0.5;
        }
    }

    if ($i < $str_length) {
        $returnstr = $returnstr . $etc;
    }

    return $returnstr;
}

/**
 * 判读用户是否手机登录
 * @return boolean
 */
function f_isMobile() {
    //最后区分ipad和移动端
    if (isset($_SERVER['HTTP_USER_AGENT']) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipad')) {
        return false;
    }

    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    //脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = [
            'nokia', 'sony', 'ericsson', 'mot', 'samsung',
            'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel',
            'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront',
            'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave',
            'nexusone', 'cldc', 'midp', 'wap', 'mobile'
        ];
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }

    return false;
}

/**
 * 
 * @Title: f_get
 * @Description: 
 * @return: return_type
 * @author: kai.gao
 * @date: 2014-11-20 下午8:46:24
 */
function f_get($name = null, $defaultValue = null) {
    return \Yii::$app->request->get($name, $defaultValue);
}

/**
 *
 * @Title: f_post
 * @Description:
 * @return: return_type
 * @author: kai.gao
 * @date: 2014-11-20 下午8:46:24
 */
function f_post($name = null, $defaultValue = null) {
    return \Yii::$app->request->post($name, $defaultValue);
}

/**
 *
 * @Title: getOrderId
 * @Description:
 * @return: $order_id
 * @author: xiangjin.shen
 * @date: 2014年12月9日 16:56:11
 */
function getOrderId($site_id) {
    $order_id = time() . rand(10000, 99999);
    return $order_id;
}

/**
 * @Title: getAfterSaleOrder
 * @Description: 生成售后单号
 * @return: return_type
 * @author: weilong.yin
 * @date: 2015-2-28 下午5:37:43
 */
function getAfterSaleOrder() {
    $order_code = 'SH' . time() . rand(10000, 99999);
    return $order_code;
}

/**
 * @Title: actionDismantle
 * @Description: 根据仓库的id 进行拆单  入参订单信息表的id --->$order_id;
 * @return: return_type
 * @author: KOUPING.SUN
 * @date: 2014-12-3 上午11:04:25
 */
function Dismantle($order_id) {
    $sql = "select supplier_id from dh_oms_order_goods where order_id = " . $order_id . " group by supplier_id";
    //$sql = "select supplier_id from dh_oms_order_goods where order_id = 94 group by supplier_id";
    $supplier_num = OmsOrderGoods::findBySql($sql)->asArray()->all();
    $supplier_nums = count($supplier_num);
    //f_d($supplier_num);
    if ($supplier_nums > 1) {
        foreach ($supplier_num as $key => $value) {
            $supplier_id = $value['supplier_id'];
            //获得同一仓库的订单商品总价
            $sql = "select goods_price from dh_oms_order_goods where order_id = " . $order_id . " and supplier_id = " . $supplier_id;
            //echo $sql;
            $hang_price_arr = OmsOrderGoods::findBySql($sql)->asArray()->all();
            // f_d($hang_price_arr);
            $hang_price = 0; //新订单的价格
            foreach ($hang_price_arr as $v) {
                $hang_price = $hang_price + $v['goods_price'];
            }
            $old_order_info = OmsOrderInfo::findOne(['id' => $order_id]);
            $old_order_info = $old_order_info->attributes;
            //var_dump($old_order_info);
            //echo "<hr/>";
            $new_order_info = new OmsOrderInfo();
            $new_order_info->order_code = getOrderId($old_order_info['site_id']);
            $new_order_info->goods_price = $hang_price;

            $new_order_info->user_id = $old_order_info['user_id'];
            $new_order_info->consignee = $old_order_info['consignee'];
            $new_order_info->company = $old_order_info['company'];
            $new_order_info->phone = $old_order_info['phone'];
            $new_order_info->tel = $old_order_info['tel'];
            $new_order_info->email = $old_order_info['email']; //OK
            $new_order_info->express_name = $old_order_info['express_name'];
            $new_order_info->express_code = $old_order_info['express_code'];
            $new_order_info->express_way = $old_order_info['express_way'];
            $new_order_info->province = $old_order_info['province'];
            $new_order_info->city = $old_order_info['city'];
            $new_order_info->district = $old_order_info['district'];
            $new_order_info->address = $old_order_info['address'];
            $new_order_info->site_id = $old_order_info['site_id']; //OK
            $new_order_info->saleman_id = $old_order_info['saleman_id'];
            $new_order_info->grid_id = $old_order_info['grid_id'];
            $new_order_info->order_time = $old_order_info['order_time'];
            $new_order_info->pay_way = $old_order_info['pay_way']; //支付方式
            $new_order_info->come_from = $old_order_info['come_from'];
            $new_order_info->description = $old_order_info['description']; //订单备注  OK
            if ($key == 0) {
                $new_order_info->credit_price = $old_order_info['credit_price'];
                $new_order_info->collecting_price = $hang_price + $old_order_info['express_price'] - $old_order_info['credit_price'];
                $new_order_info->order_price = $hang_price;
            } else {
                $new_order_info->credit_price = 0;
                $new_order_info->collecting_price = $hang_price;
                $new_order_info->order_price = $hang_price;
            }

            $new_order_info->express_price = $old_order_info['express_price'];

            $new_order_info->pay_time = time();
            $new_order_info->order_status = $old_order_info['order_status'];
            $new_order_info->supplier_id = $supplier_id; //供应商
            $new_arr = $new_order_info->save(); //拆完订单信息了
            //f_d($new_arr);
            if ($new_arr) {     //根据仓库id  生成新的订单行
                $sql = "select * from dh_oms_order_goods where order_id = " . $order_id . " and supplier_id = " . $supplier_id;
                $old_order_goods = OmsOrderGoods::findBySql($sql)->all();
                foreach ($old_order_goods as $v5) {
                    $v5->order_id = $new_order_info->id;
                    $v5->order_code = $new_order_info->order_code;
                    $out2 = $v5->save();
                    if (!$out2) {
                        $re_out = false;
                    }
                }
            } else {
                $re_out = false;
            }
        }
        //删除原订单
        $out_last = OmsOrderInfo::deleteAll(['id' => $order_id]);
        if ($out_last == 0) {
            $re_out = false;
        } else {
            $re_out = true;
        }
    } else {
        $s_id = $supplier_num[0]['supplier_id']; //供应商ID
        //$res = OmsOrderInfo::updateAll(['supplier_id'=>$s_id],['id'=>$order_id]);
        $oms_order_info = OmsOrderInfo::findOne($order_id);
        if ($oms_order_info) {
            $oms_order_info->supplier_id = $s_id;
            $res = $oms_order_info->save();
            if ($res) {
                $re_out = true;
            } else {
                $re_out = false;
            }
        } else {
            $re_out = false;
        }
    }
    return $re_out;
}

/**
 * 
 * @Title: f_mkdirs
 * @Description: 递归创建目录
 * @return: boolean
 * @author: kai.gao
 * @date: 2014-11-19 下午6:47:48
 */
function f_mkdirs($dir) {
    if (!is_dir($dir)) {
        if (!f_mkdirs(dirname($dir))) {
            return false;
        }
        if (!mkdir($dir, 0777)) {
            return false;
        }
    }
    return true;
}

/**
 * @Title: reset_passwd
 * @Description: 为客户重置密码，进行短信和邮件通知
 * @return: return_type
 * @author: weilong.yin
 * @date: 2014-12-8 下午12:59:42
 */
function reset_passwd($user_id, $mobile_phone, $email) {
    //生成6位随机数，修改客户密码
    $rand_array = range(0, 9);
    shuffle($rand_array);
    $re_passwd = implode(array_slice($rand_array, 0, 6));
    $content = '您的密码是：' . $re_passwd;
    $model = SysUser::findOne($user_id);
    $model->password = md5($re_passwd);
    $out = $model->save();

    if ($out) {
        $message_notice = (new SmsLib())->main($mobile_phone, $content);
        $email_notice = Yii::$app->mailer->compose()->setFrom(EMALL)->setTo($email)->setSubject('您的密码修改成功')->setTextBody($content)->send();
        return ($message_notice || $email_notice) ? true : false;
    }
}

/**
 * @Title: f_mailer
 * @Description: 邮件发送通知
 * @return: return_type
 * @author: weilong.yin
 * @date: 2015-5-19 下午5:12:12
 */
function f_mailer($email, $content, $subject) {
// 	$email_notice = Yii::$app->mailer->compose()->setFrom(EMAIL)->setTo($email)->setSubject($subject)->setTextBody($content)->send();
}

/**
 * @Title: f_mailer_to_me
 * @Description: 测试
 * @return: return_type
 * @author: weilong.yin
 * @date: 2015-5-21 下午6:20:12
 */
function f_mailer_to_me($email, $content, $subject) {
    $email_notice = Yii::$app->mailer->compose()->setFrom(EMAIL)->setTo($email)->setSubject($subject)->setTextBody($content)->send();
}

/**
 * @Title: f_filter
 * @Description: 数组非空过滤起 
 * @return: boolean
 * @author: kai.gao
 * @date: 2014-12-10 下午11:04:01
 */
function f_filter($val) {
    return !$val ? false : true;
}

/**
 * @Title: getmicrotime
 * @Description: 获取当前毫秒时间戳 
 * @return: number
 * @author: kai.gao
 * @date: 2014-12-16下午10:45:38
 */
function f_mtime() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float) $usec + (float) $sec);
}

function f_percent($bnum, $snum) {
    $res = round(($bnum - $snum) / $bnum, 2);
    $val = $res * 100;

    return $val;
}

/**
 * 
 * @Title: getPage
 * @Description:前台公共分页栏目 
 * @return: string
 * @author: yulong.wang
 * @date: 2014-12-23 上午10:24:09
 */
function getPage($page, $total_page) {

    $out = "<div class='pages mt20 r'>";
    $out .= "<a href='javascript:void(0);' class='prev' onClick=\"getPage(this,'prev')\">< 上一页</a>";
    if ($total_page > 5) {
        if ($page >= 3 && $total_page - 2 >= $page) {
            for ($i = $page - 2; $i <= $page + 2; $i++) {
                if ($i == $page) {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)' class='on'>" . $page . "</a>";
                } else {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)'>" . $i . "</a>";
                }
            }
        } elseif ($page + 2 > $total_page && $page <= $total_page) {
            $offset = $page - (4 - ($total_page - $page));
            for ($i = $offset; $i <= $offset + 4; $i++) {
                if ($i == $page) {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i);' class='on'>" . $page . "</a>";
                } else {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)'>" . $i . "</a>";
                }
            }
        } elseif ($page < 3 && $page >= 1) {
            for ($i = 1; $i <= 5; $i++) {
                if ($i == $page) {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)' class='on'>" . $page . "</a>";
                } else {
                    $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)'>" . $i . "</a>";
                }
            }
        }
    } else {
        for ($i = 1; $i <= $total_page; $i++) {
            if ($i == $page) {
                $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)' class='on'>" . $page . "</a>";
            } else {
                $out .= "<a href='javascript:void(0);' onClick='getPage(this,$i)'>" . $i . "</a>";
            }
        }
    }
    $out .= "<a href='javascript:void(0);' onClick=\"getPage(this,'next')\" class='next'>下一页  ></a>";
    $out .= "<div class='total'>共" . $total_page . "页</div><div class='goto'><span>到第</span>";
    $out .= "<input type='text' id='mypage'/>";
    $out .= "<span>页</span>";
    $out .= "<a class='pagesubmit' href='javascript:void(0);' onclick='getPage(this,-1)'>确定</a>";
    $out .= "</div>";
    $out .= "</div>";
    return $out;
}

/**
 *
 * @Title: getWeiXinPage
 * @Description:微信前台公共分页栏目
 * @return: string
 * @author: yulong.wang
 * @date: 2014-12-23 上午10:24:09
 */
function getWeiXinPage($page, $total_page) {
    $out = "<div id='pages'>";
    $out .= "<div class='page'>";
    $out .= "<ul>";
    if ($page > 1) {
        $out .= "<li><a href='javascript:void(0);' class='prev' onClick=\"getPage(this,'prev')\">上一页</a></li>";
    } else {
        $out .= "<li><a href='javascript:void(0);' class='prev' style='background:#C3C3C3;'>上一页</a></li>";
    }

    $out .= "<li><a href='javascript:void(0);' onClick='getPage(this,$page)' class='page_now'>" . $page . "</a></li>";

    if ($page < $total_page) {
        $out .= "<li><a href='javascript:void(0);' onClick=\"getPage(this,'next')\" class='next'>下一页 </a></li>";
    } else {
        $out .= "<li><a href='javascript:void(0);' style='background:#C3C3C3;' class='next'>下一页 </a></li>";
    }
    $out .= "<li><span class='total'>共" . $total_page . "页</li>";
    $out .= "</ul>";
    $out .= "</div>";
    $out .= "</div>";
    return $out;
}

/**
 * @Title: getRapidPage
 * @Description: 获取快速订货更多加载
 * @return: return_type
 * @author: weilong.yin
 * @date: 2014-12-30 下午12:20:26
 */
function getRapidPage($page, $total_page) {

    if ($page > $total_page) {
        return '';
    } else {
        
    }
}

/**
 * @Title: get_goods_code
 * @Description: 商品货号
 * @return: string
 * @author: weilong.yin
 * @date: 2014-12-23 上午10:31:23
 */
function get_goods_code($s_id, $b_id, $c_id) {

    $code = ($s_id . $b_id . $c_id) + 10000 + rand(0, 1000);
    $code = 'dh' . $code;
    return $code;
}

/**
 * @Title: getAccountStrength
 * @Description: 获取账户安全度
 * @param:array  账户信息
 * @return: string
 * @author: huaiyu.cui
 * @date: 2014-12-23 上午15:31:23
 */
function getAccountStrength($user_info = array()) {
    $score = 10; /* 账户得分，最低0分，最高10分 */

    if ($user_info) {
        $user_info = $_SESSION['user_info'];
    }
    /* 根据获取的账户信息是否填写来判断得分 */
    if (empty($user_info['tel'])) {
        $score -= 2;
    }
    if (empty($user_info['qq'])) {
        $score -= 2;
    }

    return $score;
}

/**
 * @Title: duanx
 * @Description: 获取最低价
 * @param string $goods_id
 * @return: 
 * @author: xiangjin.shen
 * @date: 2014年12月30日 22:30:41
 */
function f_cp($goods_id, $type = 1) {
    //库存为   0  的先下架
    $store = BaseSupplierGoods::find()->select('num_avai')->where(['id' => $goods_id])->scalar();
    if ($store == 0) {
        $store_model = BaseSupplierGoods::find()->where(['id' => $goods_id, 'status' => 1])->one();
        if ($store_model) {
            $store_model->status = 0;
            $store_model->save();
        }
    }

    $minPrice = 0;
    if ($type == 1) {//上架
        $sql = " SELECT a.`base_id`,b.`site_id` FROM dh_base_supplier_goods AS a LEFT JOIN dh_base_supp_goods_site AS b ON a.`id` = b.`supplier_goods_id`
				WHERE a.id = $goods_id && a.enable = 1 && a.is_deleted = 0 && a.status = 1 && b.status = 1 && a.num_avai > 0";
    } elseif ($type == 2) {//下架
        $sql = " SELECT a.`base_id`,b.`site_id` FROM dh_base_supplier_goods AS a LEFT JOIN dh_base_supp_goods_site AS b ON a.`id` = b.`supplier_goods_id`
				WHERE a.id = $goods_id";
    }
    if (isset($sql)) {
        $baseInfo = BaseSupplierGoods::findBySql($sql)->asArray()->all();
        foreach ($baseInfo as $key => $value) {
            $baseId = $value['base_id'];
            $siteId = $value['site_id'];
            $query = new Query();
            $query->select('(a.price + a.add_price) AS totalPrice')->from('{{%base_supplier_goods}} a')
                    ->leftJoin('{{%base_supp_goods_site}} b', 'a.id = b.supplier_goods_id')
                    ->where(['a.base_id' => $baseId, 'a.status' => 1, 'a.is_deleted' => 0, 'a.enable' => 1, 'b.site_id' => $siteId, 'b.status' => 1])
                    ->andWhere(['>', 'a.num_avai', 0]);
            $result = $query->orderBy('(a.price + a.add_price)')->one();
            if (!empty($result)) {
                $minPrice = $result['totalPrice'];
                BaseGoodsSite::updateAll(['price' => $minPrice], ['base_id' => $baseId, 'site_id' => $siteId]);
            }
        }
    }
}

/**
 * 数字转换为中文
 * @param  string|integer|float  $num  目标数字
 * @param  integer $mode 模式[true:金额（默认）,false:普通数字表示]
 * @param  boolean $sim 使用小写（默认）
 * @return string
 * @name  huaiyu.cui
 */
function f_number2chinese($num, $mode = true, $sim = true) {
    if (!is_numeric($num)) {
        return '含有非数字非小数点字符！';
    }

    $char = $sim ? array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九') : array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');

    $unit = $sim ? array('', '十', '百', '千', '', '万', '亿', '兆') : array('', '拾', '佰', '仟', '', '萬', '億', '兆');

    $retval = $mode ? '元' : '点';

    //小数部分
    if (strpos($num, '.')) {
        list($num, $dec) = explode('.', $num);

        //$dec = strval(round($dec,2));

        if ($mode) {
            $retval .= "{$char[$dec['0']]}角{$char[$dec['1']]}分";
        } else {
            for ($i = 0, $c = strlen($dec); $i < $c; $i++) {
                $retval .= $char[$dec[$i]];
            }
        }
    }

    //整数部分
    $str = $mode ? strrev(intval($num)) : strrev($num);

    for ($i = 0, $c = strlen($str); $i < $c; $i++) {
        $out[$i] = $char[$str[$i]];

        if ($mode) {
            $out[$i] .= $str[$i] != '0' ? $unit[$i % 4] : '';

            if ($i > 1 and $str[$i] + $str[$i - 1] == 0) {
                $out[$i] = '';
            }

            if ($i % 4 == 0) {
                $out[$i] .= $unit[4 + floor($i / 4)];
            }
        }
    }

    $retval = join('', array_reverse($out)) . $retval;
    return $retval;
}

/**
 * 发送短信
 * @param  string $mobile_phone
 * @param  integer $smsg
 * @return null
 * @name  xiangjin.shen
 * @time 2015年1月18日 22:18:16
 */
function f_msm($mobile_phone, $smsg) {
    include_once 'SmsLib.php';
    $sms = new SmsLib();
    $sms->main($mobile_phone, $smsg);
}

/**
 * @description:输入汉字输出拼音
 * @return: mixed
 * @author: 沈祥进
 * @date: 2015年6月17日下午2:49:17
 * @modified_date: 
 * @modified_user: 
 * @review_user:
 */
function f_pinyin($str) {
    include_once 'Pinyin.php';
    $sms = new Pinyin();
    return $sms->Pinyinout($str);
}

/**
 * 分词
 * @param  string $keywords
 * @param  integer $smsg
 * @return null
 * @name  xiangjin.shen
 * @time 2015年1月18日 22:18:16
 */
function f_scws($keywords) {
    $data = array(
        'data' => $keywords,
        'respond' => 'php',
        'charset' => 'utf8',
        'ignore' => 'no',
        'duality' => 'no',
        'traditional' => 'no',
        'multi' => '3'
    );
    $uri = "http://www.xunsearch.com/scws/api.php";

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $return = curl_exec($ch);
    curl_close($ch);
    $r = unserialize($return);
    return $r;
}

/**
 * @Title: f_price
 * @Description: 获取价格，当$num不为空时，获取的是阶梯价格
 * @return: return_type
 * @author: weilong.yin
 * @date: 2015-3-24 下午2:12:42
 * 修改：谢伟 2015年8月20日15:38:27
 */
function f_price($goods_id, $num = null) {
    $price = 0;
    $model = BaseSupplierGoods::find()->where(['id' => $goods_id])->one();

    if ($model) {
        $add_price = !empty($model->add_price) ? $model->add_price : 0;

        if ($num) {
            /**
             * 阶梯价格
             */
            $ti_price = LadderGroupPrice::getladderprice($goods_id, $num);
            /**
             * 最终价格
             */
            $price = $ti_price;
        } else {
            $price = $model->price + $add_price;
        }

        return $price;
    } else {
        return $price;
    }
}

/**
 * @Title: http_post_data
 * @Description: 51云店post方法
 * @return: return_type
 * @author: weilong.yin
 * @date: 2015-1-25 上午10:01:08
 */
function http_post_data($url, $data) {
    $post_data = array(json_encode($data));

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}

/**
 * 
 * @Title: excelTime
 * @Description: phpexcel导入表格遇到已经设置为日期格式的时间
 * @return: string
 * @author: yulong.wang
 * @date: 2015-2-2下午3:48:06
 */
function excelTime($date, $time = false) {
    if (function_exists('GregorianToJD')) {
        if (is_numeric($date)) {
            $jd = GregorianToJD(1, 1, 1970);
            $gregorian = JDToGregorian($jd + intval($date) - 25569);
            $date = explode('/', $gregorian);
            $date_str = str_pad($date [2], 4, '0', STR_PAD_LEFT)
                    . "-" . str_pad($date [0], 2, '0', STR_PAD_LEFT)
                    . "-" . str_pad($date [1], 2, '0', STR_PAD_LEFT);
            return $date_str;
        }
    } else {
        $date = $date > 25568 ? $date + 1 : 25569;
        /* There was a bug if Converting date before 1-1-1970 (tstamp 0) */
        $ofs = (70 * 365 + 17 + 2) * 86400;
        $date = date("Y-m-d", ($date * 86400) - $ofs);
    }
    return $date;
}

/**
 * 
 * @Title: 省包分页
 * @Description: 用于一个页面有多处需要分页
 * @return: string
 * @author: ning.lu
 * @date: 2015-04-09
 */
function getPages($page, $total_page, $type = "") {
    $out = "<div id='pages'>";
    $out .= "<div class='page'>";
    $out .= "<ul>";
    $out .= "<li><a href='javascript:void(0);' class='prev' onClick=\"getPages(this,'prev','$type')\"></a></li>";
    if ($total_page > 5) {
        if ($page >= 3 && $total_page - 2 >= $page) {
            for ($i = $page - 2; $i <= $page + 2; $i++) {
                if ($i == $page) {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\" class='page_now'>" . $page . "</a></li>";
                } else {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\">" . $i . "</a></li>";
                }
            }
        } elseif ($page + 2 > $total_page && $page <= $total_page) {
            $offset = $page - (4 - ($total_page - $page));
            for ($i = $offset; $i <= $offset + 4; $i++) {
                if ($i == $page) {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type');\" class='page_now'>" . $page . "</a></li>";
                } else {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\">" . $i . "</a></li>";
                }
            }
        } elseif ($page < 3 && $page >= 1) {
            for ($i = 1; $i <= 5; $i++) {
                if ($i == $page) {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\" class='page_now'>" . $page . "</a></li>";
                } else {
                    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\">" . $i . "</a></li>";
                }
            }
        }
    } else {
        for ($i = 1; $i <= $total_page; $i++) {
            if ($i == $page) {
                $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\" class='page_now'>" . $page . "</a></li>";
            } else {
                $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,$i,'$type')\">" . $i . "</a></li>";
            }
        }
    }
    $out .= "<li><a href='javascript:void(0);' onClick=\"getPages(this,'next','$type')\" class='next'></a></li>";
    $out .= "<li><span class='total'>共" . $total_page . "页，到 ";
    $out .= "<select name='pageSize' class='select_page_size' onchange=\"getPages(this,this.value,'$type')\">";
    for ($i = 1; $i <= $total_page; $i++) {
        if ($i == $page) {
            $out .= "<option value=$i selected=selected>" . $i . "</option>";
        } else {
            $out .= "<option value=$i>" . $i . "</option>";
        }
    }
    $out .= "</select>";
    $out .= " 页</li>";
    $out .= "</ul>";
    $out .= "</div>";
    $out .= "</div>";
    return $out;
}

/**
 * 根据概率抽奖
 * @param unknown $proArr
 * @return Ambigous <string, unknown>
 */
function get_rand($randNum, $proArr) {
    $result = '';
    //概率数组的总概率精度
    //$proSum = array_sum($proArr);
    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        if ($randNum > $proCur['chance'] && $randNum <= $proCur['chance2']) {
            $result = $key;
            break;
        }
    }
    return $result;
}

/**
 * 抽奖算法
 * @param unknown $params
 */
function f_prize($params) {
    $awardArr = $arr = array();
    $isNum = $isDateNum = true;
    $list = $log = $id = $str = 0;
    if ($params['start_time'] && $params['stop_time'] && $params['user_id'] && $params['user_name'] && isset($params['num']) && isset($params['active_id']) && isset($params['rate'])) {
        $startTime = $params['start_time'];
        $stopTime = $params['stop_time'];
        $nowTime = time();
        $nowDate = date('Ymd');
        if (($startTime && $nowTime < $startTime) || ($stopTime && $nowTime > $stopTime)) {
            $result['expire'] = '不在活动时间';
            return $result;
        }
        $userId = $params['user_id'];
        $userName = $params['user_name'];
        $awardNum = $params['num'];
        $activeId = $params['active_id'];
        $rate = $params['rate'];
        $sumSql = "SELECT * FROM dh_active_prize_log WHERE user_id = $userId AND award_time > $startTime";
        $awardSum = OmsOrderGoods::findBySql($sumSql)->asArray()->all();
        $num = count($awardSum);
        if ($num >= $awardNum && $awardNum > 0) {
            $isNum = false;
        }
        $dateSql = "SELECT * FROM dh_active_prize_log WHERE user_id = $userId AND award_date = $nowDate";
        $dateNum = count(OmsOrderGoods::findBySql($dateSql)->asArray()->all());
        if ($dateNum >= $rate && $rate > 0) {
            $isDateNum = false;
        }
        if (isset($params['is_prize']) && 1 == $params['is_prize']) {
            $result['is_num'] = $isNum;
            $result['is_date_num'] = $isDateNum;
            return $result;
        } else {
            if ($isNum && $isDateNum) {
                $sql = "SELECT * FROM dh_active_prize_pool WHERE active_id = $activeId";
                $awardArr = OmsOrderGoods::findBySql($sql)->asArray()->all();
                foreach ($awardArr as $key => $val) {
                    $arr[$key]['chance'] = $val['chance'];
                    $arr[$key]['chance2'] = $val['chance2'];
                }
                do {
                    $randNum = mt_rand(1, 100);
                    $rid = get_rand($randNum, $arr); //根据概率获取奖项id
                    $id = $awardArr[$rid]['id'];
                    $sleSql = "SELECT * FROM dh_active_prize_list WHERE award_id = $id";
                    $prizeNum = count(OmsOrderGoods::findBySql($sleSql)->asArray()->all());
                } while ($prizeNum >= $awardArr[$rid]['award_sum']);
                $str = $awardArr[$rid]['award_name'];
                $start_time = strtotime($awardArr[$rid]['start_time']);
                $end_time = strtotime($awardArr[$rid]['end_time']);
                $red_bag_id = $awardArr[$rid]['red_bag_id'];
                if ($red_bag_id > 0) {
                    SysRedBagUser::hdjk($red_bag_id, $userId, $start_time, $end_time);
                }
                $listSql = "INSERT INTO dh_active_prize_list (user_id,user_name,award_id,award_name,active_id) VALUES ($userId,'$userName',$id,'$str',$activeId)";
                $list = \Yii::$app->db->createCommand($listSql)->execute();
                $logSql = "INSERT INTO dh_active_prize_log (rand,user_id,active_id,award_time,award_date) VALUES ($randNum,$userId,$activeId,$nowTime,$nowDate)";
                $log = \Yii::$app->db->createCommand($logSql)->execute();
            }
            $result['is_num'] = $isNum;
            $result['is_date_num'] = $isDateNum;
            $result['list'] = $list;
            $result['log'] = $log;
            $result['id'] = $id;
            $result['data'] = $str;
            return $result;
        }
    } else {
        return "请传正确参数";
    }
}

/**
 * 关键词维护
 * @param unknown $keyword
 */
function f_keywords($id) {
    $result = array();
    if ($id) {
        $kSql = "SELECT * FROM dh_base_hot_word WHERE id = $id";
        $kResult = OmsOrderGoods::findBySql($kSql)->asArray()->all();
        if (!empty($kResult)) {
            $keyword = $kResult[0]['keywords'];
            $brandSql = "SELECT brand_id FROM dh_base_supplier_goods WHERE keywords LIKE '%$keyword%' GROUP BY brand_id";
            $brandIds = OmsOrderGoods::findBySql($brandSql)->asArray()->all();
            $typeSql = "SELECT type_id FROM dh_base_supplier_goods WHERE keywords LIKE '%$keyword%' GROUP BY type_id";
            $typeIds = OmsOrderGoods::findBySql($typeSql)->asArray()->all();
//     			$insertSql = "INSERT INTO dh_base_hot_word (keywords) VALUES ('$keyword')";
//     			$inserResult = \Yii::$app->db->createCommand($insertSql)->execute();
//     			$id = f_lastId('dh_base_hot_word');
            $bdsql = "DELETE FROM dh_base_keywords_brand_relationship WHERE kid = $id";
            \Yii::$app->db->createCommand($bdsql)->execute();
            $btsql = "DELETE FROM dh_base_keywords_type_relationship WHERE kid = $id";
            \Yii::$app->db->createCommand($btsql)->execute();
            foreach ($brandIds as $key => $brandId) {
                $brand_id = $brandId['brand_id'];
                $sql = "INSERT INTO dh_base_keywords_brand_relationship (kid,brand_id) VALUES ($id,$brand_id)";
                $brandResult = \Yii::$app->db->createCommand($sql)->execute();
            }

            foreach ($typeIds as $k => $typeId) {
                $type_id = $typeId['type_id'];
                $sql1 = "INSERT INTO dh_base_keywords_type_relationship (kid,type_id) VALUES ($id,$type_id)";
                $typeResult = \Yii::$app->db->createCommand($sql1)->execute();
            }
            $result['brand'] = $brandResult;
            $result['type'] = $typeResult;
            return $result;
        }
    } else {
        return false;
    }
}

/**
 * 获取表中最大的id
 * @param unknown $table
 * @return multitype:
 */
function f_lastId($table) {
    $id = \Yii::$app->db->createCommand("select MAX(id) from $table")->queryScalar();
    //$id = mysql_fetch_array($fh);
    return $id;
}

function f_get_keywords($keyword) {
    $result = $keywordInfo = $relate = array();
    $keyword = trim($keyword);
    if (!empty($keyword)) {
        $relateSql = "SELECT * FROM dh_base_hot_word WHERE keywords LIKE '%$keyword%' ORDER BY sort ASC";
        $relate = OmsOrderGoods::findBySql($relateSql)->asArray()->all();
        foreach ($relate as $key => $value) {
            if (0 == strcasecmp($keyword, $value['keywords'])) {
                $keywordInfo = $value;
                unset($relate[$key]);
            }
        }
        if (empty($keywordInfo)) {
            $kSql = "SELECT * FROM dh_base_new_hot_word WHERE keyword = '$keyword'";
            $kResult = OmsOrderGoods::findBySql($kSql)->asArray()->all();
            $length = strlen($keyword);
            if ($length < 20) {
                if (empty($kResult)) {
                    $sql = "INSERT INTO dh_base_new_hot_word (keyword) VALUES ('$keyword')";
                } else {
                    $s_num = $kResult[0]['s_num'] + 1;
                    $sql = "UPDATE dh_base_new_hot_word SET s_num = $s_num WHERE keyword = '$keyword'";
                }
                $newResult = \Yii::$app->db->createCommand($sql)->execute();
            }
        } else {
            $kid = $keywordInfo['id'];
            $sql = "SELECT a.brand_id,b.name FROM dh_base_keywords_brand_relationship AS a LEFT JOIN dh_base_brand AS b ON a.brand_id = b.id WHERE a.kid = $kid ORDER BY a.sort";
            $brandIds = OmsOrderGoods::findBySql($sql)->asArray()->all();
            $sql1 = "SELECT a.type_id,b.name FROM dh_base_keywords_type_relationship AS a LEFT JOIN dh_base_type AS b ON a.type_id = b.id WHERE a.kid = $kid ORDER BY a.sort";
            $typeIds = OmsOrderGoods::findBySql($sql1)->asArray()->all();
            if (!empty($brandIds)) {
                $keywordInfo['brand_id'] = $brandIds;
            } else {
                $keywordInfo['brand_id'] = [];
            }
            if (!empty($typeIds)) {
                $keywordInfo['type_id'] = $typeIds;
            } else {
                $keywordInfo['type_id'] = [];
            }
        }
        $result['keywords'] = $keywordInfo;
        $result['relate'] = array_slice($relate, 0, 7);
        return $result;
    } else {
        return false;
    }
}

/**
 * 
 * @Title: curl_post_data
 * @Description: 物流接口curl post方法
 * @return: mixed
 * @author: yulong.wang
 * @date: 2015-6-23下午3:25:47
 */
function curl_post_data($url, $json_data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($json_data) ? http_build_query($json_data) : $json_data);

    $return_json = curl_exec($ch);
    curl_close($ch);
    $return = json_decode($return_json);
    return $return;
}

/**
 * @desc 接口调用
 * @param unknown $url
 * @param unknown $json_data
 * @return mixed
 */
function curlPostData($url, $json_data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($json_data) ? http_build_query($json_data) : $json_data);

    $return_json = curl_exec($ch);
    curl_close($ch);
    $return = json_decode($return_json);
    return $return;
}

/**
 * 
 * @Title: f_get_address
 * @Description: 获取拼凑的地址
 * @return: string
 * @author: yulong.wang
 * @date: 2015-6-23下午3:59:09
 */
function f_get_address($province, $city, $district, $address) {
    $address = $province . '-' . $city . '-' . $district . '-' . $address;
    return $address;
}

/**
 * 
 * @Title: f_get_company
 * @Description: 获取收货店铺
 * @return: string
 * @author: yulong.wang
 * @date: 2015-6-23下午4:01:07
 */
function f_get_company($company, $user_id) {
    $company = '51dh-' . $company . '-' . $user_id;
    return $company;
}

/**
 * 
 * @Title: f_get_reductionAmount
 * @Description: 获取减免总金额
 * @return: number
 * @author: yulong.wang
 * @date: 2015-6-23下午4:03:25
 */
function f_get_reductionAmount($credit_price, $red_bag, $rebate, $score_price) {
    $reductionAmount = $credit_price + $red_bag + $rebate + $score_price;
    return $reductionAmount;
}

/**
 * 
 * @Title: f_out_new
 * @Description: 获取用户当前可以推荐的
 * @return: number
 * @author: xiangjin.shen
 * @date: 2015年8月7日 10:53:26
 */
function f_out_new() {
    $site_id = f_s('user_info')['site_id'];
    $user_id = f_s('user_info')['id'];
    $sql = "SELECT t1.id
                        from dh_out_new as t1 
                        LEFT JOIN dh_out_new_area as t2 ON t1.id = t2.n_id 
                        LEFT JOIN dh_out_new_user as t3 ON t1.id = t3.n_id 
                        WHERE (t2.site_id =  $site_id or t2.site_id = 0)
                        AND t1.`status` = 1 
                        AND NOT EXISTS(SELECT 1 from dh_out_new_user WHERE user_id = $user_id AND n_id = t1.id)
                        limit 1";
    $model = new OutNew;
    $res = $model->findBySql($sql)->asArray()->one();
    if ($res) {
        return $res['id'];
    } else {
        return 0;
    }
}

/**
 * @description: 验证码
 * @return: return_type
 * @author: 
 * @date: 
 * @modified_date: 
 * @modified_user: 
 * @review_user:
 */
function f_code() {
    include "vcode.php";
    //构造方法
    $vcode = new Vcode(85, 33, 4);

    //将验证码放到服务器自己的空间保存一份
    f_s('code', $vcode->getcode());
    //将验证码图片输出
    $vcode->outimg();
}

/**
 * @description:单个帐号的页面访问频率,并用text记录
 * @return: return_type
 * @author: sunkouping
 * @date: 2015年8月26日下午5:14:34
 * @modified_date: 2015年8月26日下午5:14:34
 * @modified_user: sunkouping
 * @review_user:提交不上是怎么回事啊
 */
function f_cishu($user_id, $url) {
    $redis = Yii::$app->rcache->redis;
    $key = '51web:page_view_count:' . $url . '_' . $user_id;
    $pres = [30, 30];
    $count = $redis->executeCommand('GET', [$key]);

    if ($count) {
        if ($count < $pres[0]) {
            $count = $redis->executeCommand('INCR', [$key]);
            if ($count == 1) {
                $redis->executeCommand('EXPIRE', [$key, $pres[1]]);
            }
        } else {
            $ttl = $redis->executeCommand('TTL', [$key]);
            if ($ttl == -1) {
                $redis->executeCommand('DEL', [$key]);
            } else {
//					file_put_contents("chaopin_vist.txt", $key.'时间'.date('Y-m-d H:i:s')."\n", FILE_APPEND);
//    				header("location:/active/baifen/");
//    				exit;
            }
        }
    } else {
        $redis->executeCommand('SET', [$key, 1, 'EX', $pres[1]]);
    }
}

function getYears() {
    return array(2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026);
}

function getMonths() {
    return array(01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12);
}

function getBanks() {
    return array("中国建设银行", "中国农业银行", "中国工商银行", "浦发银行", "广发银行", "中国光大银行", "招商银行", "交通银行", "中国银行", "中国邮政储蓄银行", "南京银行", "华夏银行");
}

function getExpressType($name) {
    if (stristr($name, '顺丰')) {
        return 'sf';
    }
    if (stristr($name, '圆通')) {
        return 'yt';
    }
    if (stristr($name, '申通')) {
        return 'st';
    }
    if (stristr($name, '天天')) {
        return 'tt';
    }
    if (stristr($name, '韵达')) {
        return 'yd';
    }
    if (stristr($name, 'ems')) {
        return 'ems';
    }
    if (stristr($name, '中通')) {
        return 'zt';
    }
    if (stristr($name, '汇通')) {
        return 'ht';
    }
}

?>
